package com.yuxi.Service.Impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.http.HttpSession;

import org.apache.catalina.User;
import org.drools.lang.DRLParser.exists_key_return;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.yuxi.Config.ConfigStatic;
import com.yuxi.Dao.InformationPortDao;
import com.yuxi.Dao.PowerRoleDao;
import com.yuxi.Dao.PowerUserDao;
import com.yuxi.Dao.PrisonRoleDao;
import com.yuxi.Dao.PrisonStructureDao;
import com.yuxi.Dao.UserABMapDao;
import com.yuxi.Dao.UserInfoDao;
import com.yuxi.Dao.UserPositionDao;
import com.yuxi.Dao.UserStructureDao;
import com.yuxi.Entity.InformationOperationRecord;
import com.yuxi.Entity.InformationPort;
import com.yuxi.Entity.Position;
import com.yuxi.Entity.PowerRole;
import com.yuxi.Entity.PowerUser;
import com.yuxi.Entity.PrisonRole;
import com.yuxi.Entity.PrisonStructure;
import com.yuxi.Entity.UserABMap;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Entity.UserPosition;
import com.yuxi.Entity.UserStructure;
import com.yuxi.Entity.UserView;
import com.yuxi.Request.Page;
import com.yuxi.Request.UserQuery;
import com.yuxi.Service.PrisonService;
import com.yuxi.Service.UserDoRecordService;
import com.yuxi.Service.UserService;
import com.yuxi.Util.MyMd5Util;
import com.yuxi.view.UserPowerView;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserInfoDao  userInfoDao;
	@Autowired
	private UserDoRecordService  userDoRecordService;
	@Autowired
	private PowerUserDao  powerUserDao;
	@Autowired
	private PrisonRoleDao prisonRoleDao;
	@Autowired
	private PowerRoleDao powerRoleDao;
	@Autowired
	private InformationPortDao  informationPortDao;
	@Autowired
	private PrisonStructureDao prisonStructureDao;
	@Autowired
	private UserABMapDao  userABMapDao;
	@Autowired
	private UserPositionDao userPositionDao;
	@Autowired
	private UserStructureDao userStructureDao;

	private Logger logger=LoggerFactory.getLogger(UserServiceImpl.class);
	@Override
	public UserInfo userLogin(String userAccount, String pwd,String ip) {
		UserInfo u=userInfoDao.login(userAccount, pwd);
		if(u!=null){
			if(!u.isEnable()){
				logger.info("用户："+u.getUserAccount()+" IP:"+ip+"登录失败[账户已被停用]");
			}
			userDoRecordService.addUserLoginRecord(u.getUserId(), ip,u.getUserName());
			logger.info("用户："+u.getUserAccount()+" IP:"+ip+"登录成功!");
		}else{
			logger.warn("IP:"+ip+"登录失败!");
		}		
		return u;
	}
	@Override
	public UserInfo getCurLoginUser(HttpSession session) {
		UserInfo u=(UserInfo)session.getAttribute("user");		
		return u;
	}
	@Override
	public UserInfo userCreateOneUser(UserInfo createUser, UserInfo user, String ip,int positionId,String positionName ,int structureId,String structureName ,int roleId) {
		try{
			createUser.setCreateUserid(user.getUserId());
			createUser.setUserPassword(MyMd5Util.stringToMd5(createUser.getUserPassword()));
			createUser.setCreateTimg(System.currentTimeMillis());
			createUser=userInfoDao.addUser(createUser);
			PowerUser pUser=new PowerUser(createUser.getUserId(), roleId);
			powerUserDao.addPowerUser(pUser);
			UserPosition userPosition =new UserPosition(createUser.getUserId(), createUser.getUserName(), positionId, positionName);
			userPositionDao.addUserPosition(userPosition);
			UserStructure userStructure=new UserStructure();
			userStructure.setStructureId(structureId);
			userStructure.setStructureName(structureName);
			userStructure.setUserId(createUser.getUserId());
			userStructure.setUserName(createUser.getUserName());
			System.out.println(userStructure.toString());
			userStructureDao.addUserStructure(userStructure);
			userDoRecordService.createUserDoRecord(0, user.getUserId(), ip, ConfigStatic.DOTYPETABLE.get("UserAdd"), "添加用户",user.getUserName());
			return createUser;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	@Override
	public PrisonStructure getUserPrisonArea(int userId) {		;
		List<PrisonStructure> pList=prisonStructureDao.getAllStructure();
		PrisonStructure prisonStructure=prisonStructureDao.getStructure(userId);
		return findPrison(prisonStructure,pList);
	}
	
	private PrisonStructure findPrison(PrisonStructure p,List<PrisonStructure> plist){
		String keyStr=p.getValue();
		if(keyStr.equals("Prison")||keyStr.equals("PrisonArea")){
			return p;
		};
		int sId=p.getSuperId();
		ListIterator<PrisonStructure> it=plist.listIterator();
		for(int i=0;i<plist.size();i++){
			PrisonStructure cur=plist.get(i);
			if(cur.getId()==sId){
				return findPrison(cur,plist);
			}
		}				
		return p;		
	}
	@Override
	public List<UserInfo> userGetStructUserList(int structId) {
		return prisonStructureDao.getStructureALLUser(structId);
	}
	@Override
	public Page<UserView> getStructUserList(int structId,UserQuery userQuery,Page<UserView> p) {
		 return userInfoDao.getStruectureAllUser(userQuery, structId, p);
		  
	}
	@Override
	public List<PrisonStructure> userGetsafetyPortList(UserInfo u) {		
		PowerUser p=powerUserDao.getPowerUserByUserId(u.getUserId());
		PrisonRole prisonRole=prisonRoleDao.getPrisonRole(p.getRoleId());		;
		List<PrisonStructure> pList=prisonStructureDao.getAllStructure();
		PrisonStructure pStruct=findPrison(prisonRole.getPrisonStructure(),pList);		
		List<PrisonStructure>  rsList=new ArrayList<PrisonStructure>();	
		PrisonStructure pArea=findPrison(pStruct,pList);
		if(pStruct.getValue().equals("PrisonArea")){
			rsList=findSafetyPortList("Mouth", pArea.getId(),pStruct,pList);
		}else{
			rsList=findSafetyPortList("Department",pArea.getId(),pStruct,pList);
		}
		return rsList;
	}
	
	private List<PrisonStructure> findSafetyPortList(String str,int superId,PrisonStructure pStruct,List<PrisonStructure> pList){
		List<PrisonStructure>  rsList=new ArrayList<PrisonStructure>();		
		Iterator it=pList.iterator();
		while(it.hasNext()){
			PrisonStructure cur=(PrisonStructure) it.next();	
			if(cur.getValue().equals(str)&&cur.getSuperId()==superId){
				rsList.add(cur);
			}
		}
		return rsList;
	}
	@Override
	public Page<UserView> getUserList(UserQuery userQuery, UserInfo u,Page<UserView> p) {
		Page<UserView> rsP=userInfoDao.getCreateUserList(userQuery, u.getUserId(), p);
		List<UserView> uList=rsP.getList();			
		List<UserView> rsList=new ArrayList<UserView>();		
		for(int i=0;i<uList.size();i++){
			UserView curU=(UserView)uList.get(i);
			PrisonRole pR=prisonRoleDao.getPrisonRole(curU.getRoleId());
			PrisonStructure pS=pR.getPrisonStructure();
			curU.setRoleName(pR.getName());	
			curU.setStructId(Integer.toString(pS.getId()));
			curU.setStructName(pS.getName());			
			rsList.add(curU);
		}	
		rsP.setList(rsList);
		return rsP;
	}
	
	@Override
	public PowerRole getRolePower(UserInfo u) {		
		return powerRoleDao.getUserRolePower(u.getUserId());
	}
	@Override
	public List<UserInfo> getPrisonHeaderList(UserInfo u) {		
		return userGetStructUserList(getUserPrisonArea(u.getUserId()).getId());		
	}
	
	@Override
	public List<UserInfo> getPrisonHeader(Integer pId) {
		return userInfoDao.getPrisonHeader(pId);		
	}
	@Override
	public List<UserInfo> getPrisonViceHeader(Integer pId) {
		return userInfoDao.getPrisonViceHeader(pId);	
	}
	@Override
	public boolean stopUserById(Integer userId,UserInfo user) {
		UserInfo u=userInfoDao.getUser(userId);
		if(u.getCreateUserid()!=user.getUserId()){
			return false;
		}else{
			u.setEnable(false);
			userInfoDao.modifly(u);
		}
		return true;
	}
	@Override
	public UserPowerView getUserPowerViewByUserId(UserInfo user) {
		UserPowerView upView=new UserPowerView();
		PowerRole powerRole=getRolePower(user);
		Position position=new Position();
		position=userPositionDao.getPositionByUser(user.getUserId());
		List<InformationPort> powerPort=informationPortDao.getUserPort(powerRole.getRoleId());
		
		upView.setPowerPort(powerPort);
		upView.setPowerRole(powerRole);		
		upView.setPosition(position);			
		upView.setMaxStructure(getUserPrisonArea(userStructureDao.getStructureByUserId(user.getUserId()).getStructureId()));
		
		
		return upView;
	}
	@Override
	public UserPowerView curLoginUserPowerView(HttpSession session) {		
		UserPowerView u=(UserPowerView)session.getAttribute("userPowerView");
		if(u==null){
			 u=getUserPowerViewByUserId(getCurLoginUser(session));
		}
		System.out.println(u.getPowerRole());
		return u;
	}
	@Override
	public boolean enableUserById(Integer userId, UserInfo user) {
		UserInfo u=userInfoDao.getUser(userId);
		if(u.getCreateUserid()!=user.getUserId()){
			return false;
		}else{
			u.setEnable(true);
			userInfoDao.modifly(u);
		}
		return true;
	}
	@Override
	public boolean userModify(UserInfo user, Integer roleId) {
		try{			
			UserInfo newUser=userInfoDao.getUser(user.getUserId());
			newUser.setIdNumber(user.getIdNumber());
			newUser.setUserName(user.getUserName());
			newUser.setPhone(user.getPhone());
			newUser.setUserAccount(user.getUserAccount());
			newUser.setUserHeadPortait(user.getUserHeadPortait());
			userInfoDao.modifly(newUser);
			PowerUser newPower=powerUserDao.getPowerUserByUserId(newUser.getUserId());
			newPower.setRoleId(roleId);
			powerUserDao.modifly(newPower);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public boolean createMapATOB(UserInfo userA, UserInfo userB) {
		UserABMap uMap=new UserABMap(userA.getUserId(), userA.getUserName(), userB.getUserName(), userB.getUserId());
		UserABMap uMaps=userABMapDao.addUserABMap(uMap);
		if(uMaps!=null){
			return true;
		}else{
			return false;
		}
		
	}
	@Override
	public boolean upDateMapATOB(UserInfo doUser, UserInfo modifiUser) {
		try{
			UserABMap usermap=userABMapDao.getUserABMapByUserId(doUser.getUserId());
			
			if(usermap!=null){
				if(usermap.getaUserId()==doUser.getUserId()){
					usermap.setbUserId(modifiUser.getUserId());
					usermap.setbUserName(modifiUser.getUserName());
				}else{
					usermap.setaUserId(modifiUser.getUserId());
					usermap.setaUserName(modifiUser.getUserName());
				}
				userABMapDao.modifiUserMap(usermap);;
			}else{
				createMapATOB(doUser, modifiUser);
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	
	@Override
	public boolean userModify(UserInfo user, Integer roleId,UserPosition userPosition) {
		try{
			
			UserInfo newUser=userInfoDao.getUser(user.getUserId());

			newUser.setIdNumber(user.getIdNumber());
			
			newUser.setUserName(user.getUserName());
			newUser.setPhone(user.getPhone());
			newUser.setUserAccount(user.getUserAccount());
			newUser.setUserHeadPortait(user.getUserHeadPortait());
			userInfoDao.modifly(newUser);
			UserPosition uPosition = new UserPosition();
			uPosition= (userPositionDao.getPositionByUserId(newUser.getUserId()).get(0));
			uPosition.setUserId(newUser.getUserId());
			uPosition.setUserName(newUser.getUserName());
			uPosition.setPositionId(userPosition.getPositionId());
			uPosition.setPositionName(userPosition.getPositionName());
			userPositionDao.modifly(uPosition);
			PowerUser newPower=powerUserDao.getPowerUserByUserId(newUser.getUserId());
			newPower.setRoleId(roleId);
			powerUserDao.modifly(newPower);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public boolean userModify(UserInfo user, Integer roleId,UserPosition userPosition,int structureId,String  structureName) {
		try{
			
			UserInfo newUser=userInfoDao.getUser(user.getUserId());

			newUser.setIdNumber(user.getIdNumber());
			newUser.setUserPassword(MyMd5Util.stringToMd5(user.getUserPassword()));
			newUser.setUserName(user.getUserName());
			newUser.setPhone(user.getPhone());
			newUser.setUserAccount(user.getUserAccount());
			newUser.setUserHeadPortait(user.getUserHeadPortait());
			userInfoDao.modifly(newUser);
			UserPosition uPosition = new UserPosition();
			uPosition= (userPositionDao.getPositionByUserId(newUser.getUserId()).get(0));
			uPosition.setUserId(newUser.getUserId());
			uPosition.setUserName(newUser.getUserName());
			uPosition.setPositionId(userPosition.getPositionId());
			uPosition.setPositionName(userPosition.getPositionName());
			userPositionDao.modifly(uPosition);
			PowerUser newPower=powerUserDao.getPowerUserByUserId(newUser.getUserId());
			newPower.setRoleId(roleId);
			powerUserDao.modifly(newPower);
			UserStructure newStructure =userStructureDao.getStructureByUserId(user.getUserId());
			newStructure.setStructureId(structureId);
			newStructure.setStructureName(structureName);
			newStructure.setUserId(user.getUserId());
			newStructure.setUserName(user.getUserName());
			userStructureDao.modifyUserStructure(newStructure);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public UserInfo getUserBByUserA(UserInfo userA) {
		UserABMap usermap=userABMapDao.getUserABMapByUserId(userA.getUserId());
		UserInfo userb=new UserInfo();
		if(usermap!=null){			
			if(usermap.getaUserId()==userA.getUserId()){
				userb.setUserId(usermap.getbUserId());
				userb.setUserName(usermap.getbUserName());
			}else{
				userb.setUserId(usermap.getaUserId());
				userb.setUserName(usermap.getaUserName());
			}
		}else{
			return null;
		}
		
		return userb;
	}
	

}
